package com.wewins.fota.sys.task;

import com.alibaba.fastjson.JSONObject;
import com.wewins.fota.bean.bo.ServerInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.concurrent.TimeUnit;

import static com.wewins.fota.constant.FotaConst.REDIS_KEY_SERVER_INFOS;

@Slf4j
@Component
public class ServerHeartbeatTask {
    private final ServerInfo serverInfo;
    private final RedisTemplate<String, String> template;

    public ServerHeartbeatTask(ServerInfo serverInfo, RedisTemplate<String, String> template) {
        this.serverInfo = serverInfo;
        this.template = template;
    }

    @PostConstruct
    @Scheduled(cron = "*/30 * * * * ?")
    public void registerAndHeartbeat() {
        template.opsForValue().set(
                String.format(REDIS_KEY_SERVER_INFOS, serverInfo.getKey()),
                JSONObject.toJSONString(serverInfo),
                32,
                TimeUnit.SECONDS
        );
    }
}
